require 'net/http'

Handler = Proc.new do |req, res|
  regex = {
    date: '\W[0-9]{1,2}\/[0-9]{1,2}-[0-9]{1,2}\/[0-9]{1,2}.*)',
    exclude: '\W[0-9]{1,2}\/[0-9]{1,2}-[0-9]{1,2}\/[0-9]{1,2})'
  }

  users = {
    diana: "(Lejonet#{regex[:date]}(?=Jungfru#{regex[:exclude]}",
    beyar: "(Oxen#{regex[:date]}(?=Tvillingarna#{regex[:exclude]}"
  }

  config = {
    host: 'https://astro.elle.se'
  }

  query = req.query['name'] || 'diana'
  user = users.fetch(query.to_sym)
  # user = users[:diana]

  uri = URI(config[:host])
  strip_html = /<\/?[^>]*>/
  raw_response = Net::HTTP.get_response(uri)
  response = raw_response
    .body
    .gsub(strip_html, '')
    .scan(/#{user}/)
    .flatten
    .first

  encoded = response.force_encoding('utf-8')

  res.status = 200
  res['Content-Type'] = 'text/plain; charset=utf-8'
  res['Access-Control-Allow-Credentials'] = true

  res.header['Access-Control-Allow-Origin'] = '*'
  res.header['Access-Control-Allow-Methods'] = 'GET'
  res.header['Vary'] = 'Access-Control-Request-Headers'
  res.header['Access-Control-Allow-Headers'] = 'Content-Type, Accept'
  res.header['Access-Control-Request-Method'] = '*'

  res.body = encoded

  # encoded = response
  # encoded
end

# puts Handler.call(nil, nil)
